import yaml
import os
from typing import Dict, Any

class ConfigManager:
    """配置管理器"""
    
    def __init__(self):
        # 构造相对于此文件位置的绝对路径
        base_dir = os.path.dirname(os.path.abspath(__file__))
        config_file = os.path.join(base_dir, "config.yaml")
        self.config_file = config_file
        self.config = self.load_config()
        
    def load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        if not os.path.exists(self.config_file):
            # 如果配置文件不存在，创建默认配置
            self.create_default_config()
            
        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                config = yaml.safe_load(f)
            return config
        except FileNotFoundError:
            print(f"配置文件未找到: {self.config_file}")
            print("请确保 config.yaml 文件与 config_manager.py 在同一目录下。")
            return {}
        except Exception as e:
            print(f"加载配置文件失败: {str(e)}")
            return self.get_default_config()
    
    def save_config(self) -> bool:
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                yaml.dump(self.config, f, allow_unicode=True)
            return True
        except Exception as e:
            print(f"保存配置文件失败: {str(e)}")
            return False
    
    def get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        # This can be simplified as we now have a default config.yaml
        return {}

    def create_default_config(self):
        """创建默认配置文件"""
        # This logic is mostly for ensuring a config exists if deleted.
        # The default values are now maintained in config.yaml.
        default_config = self.get_default_config()
        if not default_config:
            # In a real scenario, you might have a truly default hardcoded config here.
            print("默认配置文件模板不存在，将创建一个空文件。")
        
        # Ensure directory exists
        os.makedirs(os.path.dirname(self.config_file), exist_ok=True)

        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                 yaml.dump(default_config, f, allow_unicode=True)
            print(f"已创建默认配置文件: {self.config_file}")
        except Exception as e:
            print(f"创建默认配置文件失败: {str(e)}")
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        value = self.config
        
        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default
    
    def set(self, key: str, value: Any) -> bool:
        """设置配置值"""
        keys = key.split('.')
        config_ref = self.config
        
        for k in keys[:-1]:
            config_ref = config_ref.setdefault(k, {})
        
        config_ref[keys[-1]] = value
        return self.save_config()

# 全局配置管理器实例
# 确保在模块加载时只初始化一次
if 'config_manager' not in globals():
    config_manager = ConfigManager()

def get_config() -> ConfigManager:
    """获取全局配置管理器"""
    return config_manager

def get_config_value(key: str, default: Any = None) -> Any:
    """获取配置值"""
    return config_manager.get(key, default) 